const Router = require('@koa/router')
const bodyParser = require('koa-bodyparser')
const { PassThrough } = require('stream')
const router = new Router()

const AiTalk = require('../dp/instance')

router.use(bodyParser())

router.post('/dpTalk', async (ctx, next) => {
  const { content } = ctx.request.body

  // 设置响应头为流式传输
  ctx.set({
    'Content-Type': 'text/plain; charset=utf-8',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
    'Transfer-Encoding': 'chunked'
  })

  ctx.status = 200

  try {
    // 中间件作为流通层 完全不处理数据 交由前端处理
    const stream = await AiTalk.dpChat(content)
    // 创建转换流
    const transformStream = new PassThrough()

    // 立即设置响应体
    ctx.body = transformStream

    // 异步处理 OpenAI 流
    ;(async () => {
      try {
        for await (const chunk of stream) {
          const content = chunk.choices[0]?.delta?.content || ''
          if (content) {
            // 直接写入转换流
            transformStream.write(content)
          }
        }
        transformStream.end()
      } catch (error) {
        console.error('流处理错误:', error)
        transformStream.end()
      }
    })()
  } catch (error) {
    console.error('流式传输错误:', error)
    ctx.body = { code: 500, message: '流式传输失败' }
  }
})

module.exports = router
